package personal.hn.newjava.repository.impl;

import personal.hn.newjava.repository.SysUSerCustomRepository;
import personal.hn.newjava.utils.SqlUtil;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

import java.util.Arrays;

public class SysUSerCustomRepositoryImpl implements SysUSerCustomRepository {
    @PersistenceContext
    private EntityManager entityManager;
    @Override
    public int batchInsertUserRole(Long[] userIds, Long[] roleIds) {
        if(!Arrays.stream(roleIds).allMatch(id -> id == null)) {
            int length = userIds.length > roleIds.length ? roleIds.length : userIds.length;
            StringBuffer sql = new StringBuffer();
            sql.append("insert into sys_user_role(user_id,role_id) values");
            sql.append(SqlUtil.getBatchInsertSqlStr(length, 2));
            Query query = entityManager.createNativeQuery(sql.toString());
            int paramIndex = 1;
            for (int i = 0; i < length; i++) {
                query.setParameter(paramIndex++, userIds[i]);
                query.setParameter(paramIndex++, roleIds[i]);
            }
            return query.executeUpdate();
        }
        return 0;
    }


}
